var MAP_DICT = {};

layui.define
(['YsGridBtn', 'YsGridTree'], function (exports) {
    $.ajax({
        type: "POST",
        url: '/api/inter/ysDict/listAll',
        data: {},
        success: function (res) {
            if (res.code == 0) {
            	MAP_DICT = res.data
            } else {
                alert('加载字典选项失败');
            }
        }
    });
	/* 定义object对象【start】 */
	var object = {
		init:function (c) {this.f(c);this.load();return object;},
		c: {data:[]}, // 配置项
		f: function (c) { // 数据初始化
			var s = new Date().getTime(),t = this;
			if(!c.id_panel_content) {
				alert('页面容器的ID属性未指定，请检查！');
			}
			/* YsGrid基本配置，格式：
			{
				"id_panel_content": "xxxxxxx",
				"conditions": [{}]
			}
			 */
			t.c = c;
			t.c.id = 'id_' + (new Date().getTime());
			t.c.id_panel_content = c.id_panel_content; // 页面容器ID
			t.c.id_grid_panel = 'id_grid_panel_' + (new Date().getTime()); // 主表格所在容器ID
			t.c.id_table_main = 'id_table_main_' + (new Date().getTime()); // 主表格ID
			t.c.id_panel_search_form = 'id_panel_search_form_' + (new Date().getTime()); // 搜索表单所在容器ID
			t.c.id_tree = 'id_tree_' + (new Date().getTime()); // 树ID
		},
		load:function () { // 加载控件
			var t = this;
			
			if (t.c.templateType == 'none') {
				return;
			} else if (t.c.templateType == 'normal_list') {
				this.loadHTMLNormal();
			} else if (t.c.templateType == 'tree_with_list') {
				this.loadHTMLTreeGrid();
				this.loadTree();
			}
			this.initFormItem();
			this.loadGridTableMain();
			this.listenBtn();
		},
		loadHTMLTreeGrid: function() {
			var t = this;
			var h =
				 `<!-- 树面板【start】 -->`
				+ `<div style="height: 100vh; width: 17%; float: left;">`
					+ `<div style="overflow: auto; padding-top: 0.2rem; height: 100%;">`
						+ `<div id="` + t.c.id_tree + `">`
						+ `</div>`
					+ `</div>`
				+ `</div>`
				+ `<!-- 树面板【end】 -->`
				+ `<!-- 表格面板【start】 -->`
				+ `<div style="height: 100%; width: 83%; float: left;">`
					+ `<div class="display_flex" style="height: 100%;">`
						+ `<!-- 左边面板【start】 -->`
						+ `<div id="` + t.c.id_grid_panel + `" class="ysui-col flex_none width_percent_83">`
							+ `<table class="layui-hide" id="` + t.c.id_table_main + `" lay-filter="` + t.c.id_table_main + `"></table>`
						+ `</div>`
						+ `<!-- 左边面板【end】 -->`
						+ `<!-- 右边面板【start】 -->`
						+ `<div id="` + t.c.id_panel_search_form + `" class="flex_1" style="background-color: #ffffff;height: 100%;">`
							+ `<div id="` + t.c.id + `" style="background-color: #ffffff;">`
								+ `<div style="background: rgb(0, 135, 250);">`
									+ `<div data-id="icon-to-hide-and-show" data-action="hide">`
										+ `<i class="layui-icon layui-icon-spread-left" style="color: #fff;"></i>`
										+ `<span style="color: white; margin-left: 100px;">搜索条件</span>`
									+ `</div>`
									+ `<div data-id="icon-to-hide-and-show" data-action="show" class="text_align_center" style="display: none;">`
										+ `<i class="layui-icon layui-icon-shrink-right" style="color: #fff;"></i>`
									+ `</div>`
								+ `</div>`
								+ this.loadForm()
							+ `</div>`
						+ `</div>`
						+ `<!-- 右边面板【end】 -->`
					+ `</div>`
				+ `</div>`
				+ `<!-- 表格面板【end】 -->`;
			$('#'+this.c.id_panel_content).html(h);
		},
		loadTree:function () { // 加载树
			var t = this;
			layui.YsGridTree.init({menuId: t.c.menuId, id_tree: t.c.id_tree, parentObj: t});
		},
		loadHTMLNormal: function() {
			var t = this;
			var h =
				 `<!-- 左边面板【start】 -->`
				+ `<div id="` + t.c.id_grid_panel + `" class="ysui-col flex_none width_percent_83">`
					+ `<table class="layui-hide" id="` + t.c.id_table_main + `" lay-filter="` + t.c.id_table_main + `"></table>`
				+ `</div>`
				+ `<!-- 左边面板【end】 -->`
				+ `<!-- 右边面板【start】 -->`
				+ `<div id="` + t.c.id_panel_search_form + `" class="flex_1" style="background-color: #ffffff;height: 100%;">`
					+ `<div id="` + t.c.id + `" style="background-color: #ffffff;">`
						+ `<div style="background: rgb(0, 135, 250);">`
							+ `<div data-id="icon-to-hide-and-show" data-action="hide">`
								+ `<i class="layui-icon layui-icon-spread-left" style="color: #fff;"></i>`
								+ `<span style="color: white; margin-left: 100px;">搜索条件</span>`
							+ `</div>`
							+ `<div data-id="icon-to-hide-and-show" data-action="show" class="text_align_center" style="display: none;">`
								+ `<i class="layui-icon layui-icon-shrink-right" style="color: #fff;"></i>`
							+ `</div>`
						+ `</div>`
						+ this.loadForm();
					+ `</div>`
				+ `</div>`
				+ `<!-- 右边面板【end】 -->`;
			$('#'+this.c.id_panel_content).html(h);
		},
		loadForm:function () { // 加载表单
	    	var t = this;
			var h = ``;
				h += `<form class="layui-form margin_0" data-id="form-for-search" style="padding: 0.2rem;">`;
					h += `<div class="layui-form-item margin_0">`;
					for(var i=0;i<t.c.conditions.length;i++){
						h += this.loadFormItem(t.c.conditions[i], i);
					}
					h += `</div>`;
					
					h += this.loadFormBtn();
				h += `</form>`;
			return h;
		},
		loadFormItem:function (condition, index) { // 加载单个表单
			var h = ``;
			if(condition.type == 't_hidden') {
				h = this.loadFormItemHidden(condition, index);
			} else if(condition.type == 't_text') {
				h = this.loadFormItemInput(condition, index);
			} else if(condition.type == 't_year') {
				h = this.loadFormItemYear(condition, index);
			} else if(condition.type == 't_monthly') {
				h = this.loadFormItemMonth(condition, index);
			} else if(condition.type == 't_date') {
				h = this.loadFormItemDate(condition, index);
			} else if(condition.type == 't_datetime') {
				h = this.loadFormItemDatetime(condition, index);
			} else if(condition.type == 't_dropdown') {
				h = this.loadFormItemDropdown(condition, index);
			} else if(condition.type == 't_buttontext') {
				h = this.loadFormItemButtonText(condition, index);
			}
			return h;
		},
		loadFormItemHidden:function (condition, index) { // 加载表单-隐藏域
			var h =
				`<input name="` + condition.code + `" type="hidden" cond-range-type="` + condition.rangeType + `" value="` + condition.value + `">`;
			return h;
		},
		loadFormItemInput:function (condition, index) { // 加载表单-输入框
			var h =
				`<div class="layui-inline layui-col-xs12 layui-col-md12 margin_1" data-index="` + index + `">`
					+ `<label class="layui-form-label padding_4_0 width_80 text_overflow_ellipsis">` + condition.name + `:</label>`
					+ `<div class="layui-input-block display_flex height_30 min_height_30 line_height_30 margin_l_90">`
						+ `<input data-form-filter="ys-search-form-item" data-index="` + index + `" data-filter="ysui_input_text" data-code="` + condition.code + `" type="text" autocomplete="off" placeholder="` + condition.placeHolder + `" cond-range-type="` + condition.rangeType + `" value="` + (condition.value ? condition.value : '') + `" class="layui-input height_30" style="border: solid 0.1px; border-color: #B5B5B5; width:90%;">`
						+ `<i class="layui-icon layui-icon-close-fill height_30 min_height_30" title="清空此条件" data-index="` + index + `"></i>`
					+ `</div>`
				+ `</div>`;
			return h;
		},
		loadFormItemYear:function (condition, index) { // 加载表单-年份选择框（YYYY）
			var h =
				`<div class="layui-inline layui-col-xs12 layui-col-md12 margin_1">`
					+ `<label class="layui-form-label padding_4_0 width_80 text_overflow_ellipsis">` + condition.name + `:</label>`
					+ `<div class="layui-input-block display_flex height_30 min_height_30 line_height_30 margin_l_90">`
						+ `<input data-form-filter="ys-search-form-item" readonly data-index="` + index + `" data-filter="ysui_input_year" data-code="` + condition.code + `" type="text" autocomplete="off" placeholder="` + condition.placeHolder + `" cond-range-type="` + condition.rangeType + `" value="` + (condition.value ? condition.value : '') + `" class="layui-input height_30" style="border: solid 0.1px; border-color: #B5B5B5; width:90%;">`
						+ `<i class="layui-icon layui-icon-close-fill height_30 min_height_30" title="清空此条件" data-index="` + index + `"></i>`
					+ `</div>`
				+ `</div>`;
			return h;
		},
		loadFormItemMonth:function (condition, index) { // 加载表单-月份选择框（YYYY-MM）
			var h =
				`<div class="layui-inline layui-col-xs12 layui-col-md12 margin_1">`
					+ `<label class="layui-form-label padding_4_0 width_80 text_overflow_ellipsis">` + condition.name + `:</label>`
					+ `<div class="layui-input-block display_flex height_30 min_height_30 line_height_30 margin_l_90">`
						+ `<input data-form-filter="ys-search-form-item" readonly data-index="` + index + `" data-filter="ysui_input_month" data-code="` + condition.code + `" type="text" autocomplete="off" placeholder="` + condition.placeHolder + `" cond-range-type="` + condition.rangeType + `" value="` + (condition.value ? condition.value : '') + `" class="layui-input height_30" style="border: solid 0.1px; border-color: #B5B5B5; width:90%;">`
						+ `<i class="layui-icon layui-icon-close-fill height_30 min_height_30" title="清空此条件" data-index="` + index + `"></i>`
					+ `</div>`
				+ `</div>`;
			return h;
		},
		loadFormItemDate:function (condition, index) { // 加载表单-日期选择框（YYYY-MM-DD）
			var h =
				`<div class="layui-inline layui-col-xs12 layui-col-md12 margin_1">`
					+ `<label class="layui-form-label padding_4_0 width_80 text_overflow_ellipsis">` + condition.name + `:</label>`
					+ `<div class="layui-input-block display_flex height_30 min_height_30 line_height_30 margin_l_90">`
						+ `<input data-form-filter="ys-search-form-item" readonly data-index="` + index + `" data-filter="ysui_input_date" data-code="` + condition.code + `" type="text" autocomplete="off" placeholder="` + condition.placeHolder + `" cond-range-type="` + condition.rangeType + `" value="` + (condition.value ? condition.value : '') + `" class="layui-input height_30" style="border: solid 0.1px; border-color: #B5B5B5; width:90%;">`
						+ `<i class="layui-icon layui-icon-close-fill height_30 min_height_30" title="清空此条件" data-index="` + index + `"></i>`
					+ `</div>`
				+ `</div>`;
			return h;
		},
		loadFormItemDatetime:function (condition, index) { // 加载表单-时间选择框（HH:MM:SS）
			var h =
				`<div class="layui-inline layui-col-xs12 layui-col-md12 margin_1">`
					+ `<label class="layui-form-label padding_4_0 width_80 text_overflow_ellipsis">` + condition.name + `:</label>`
					+ `<div class="layui-input-block display_flex height_30 min_height_30 line_height_30 margin_l_90">`
						+ `<input data-form-filter="ys-search-form-item" readonly data-index="` + index + `" data-filter="ysui_input_datetime" data-code="` + condition.code + `" type="text" autocomplete="off" placeholder="` + condition.placeHolder + `" cond-range-type="` + condition.rangeType + `" value="` + (condition.value ? condition.value : '') + `" class="layui-input height_30" style="border: solid 0.1px; border-color: #B5B5B5; width:90%;">`
						+ `<i class="layui-icon layui-icon-close-fill height_30 min_height_30" title="清空此条件" data-index="` + index + `"></i>`
					+ `</div>`
				+ `</div>`;
			return h;
		},
		loadFormItemDropdown:function (condition, index) { // 加载表单-下拉选择框
			var h = ``;
				h += `<div class="layui-inline layui-col-xs12 layui-col-md12 margin_1">`;
					h += `<label class="layui-form-label padding_4_0 width_80 text_overflow_ellipsis">` + condition.name + `:</label>`;
					h += `<div class="layui-input-block display_flex height_30 min_height_30 line_height_30 margin_l_90">`
						h += `<select data-form-filter="ys-search-form-item" data-index="` + index + `" data-code="` + condition.code + `" cond-range-type="` + condition.rangeType + `">`;
						for (var i = 0; i < condition.optionArr.length; i++) {
							var option = condition.optionArr[i];
							h += `<option value="` + option.value + `">` + option.name + `</option>`;
						}
						h += `</select>`;
					h += `</div>`;
				h += `</div>`;
			return h;
		},
		loadFormBtn:function () { // 加载按钮
			var h =
				`<div style="width:100%; text-align: center;">`
					+ `<a data-filter="filter_form_search" class="layui-btn layui-btn-normal layui-btn-xs search_btn"><i class="layui-icon layui-icon-search"></i> 查询</a>`
					+ `<button data-filter="filter_form_clear" type="button" class="layui-btn layui-btn-danger layui-btn-xs" lay-filter="filter_form_search_clear"><i class="layui-icon layui-icon-close"></i> 清空</button>`
				+ `</div>`;
			return h;
		},
		loadGridTableMain:function () { // 加载主表格
			var t = this;
			
			// 创建渲染实例
			layui.table.render({
				elem: '#' + t.c.id_table_main
				,url: t.c.pathGridRequest // 此处为静态模拟数据，实际使用时需换成真实接口
				,toolbar: '#toolbarDemo'
				,defaultToolbar: ['filter', {
						title: '刷新页面'
						,layEvent: 'LAYTABLE_REFRESH'
						,icon: 'layui-icon-refresh'
					}]
				,height: 'full-0' // 最大高度减去其他容器已占有的高度差
				,limit : 50
				,limits : [50,100,200,500]
				,where: t.getConds()
				,cellMinWidth: 95
				,totalRow: true // 开启合计行，true开启，false关闭
				,page: true
				,request: {
					pageName: 'page',
					limitName: 'size'
				}
				,even: false // 开启隔行背景
				,totalRow: true
				,cols: t.c.cols
				,done: function(res){
					var id = this.id;
		            
					// 文本框编辑事件
					$('input[lay-filter="_input_filter_text_on_table"]').on('change',function (e) {
						var table = layui.table;
						var value = $(this).val();
					    var tdElem = $(this).closest('td');
					    var trElem = tdElem.closest('tr');
					    var tableView = trElem.closest('.layui-table-view');
					    table.cache[t.c.id_table_main][trElem.data('index')][tdElem.data('field')] = value;
						
						var dataCommit = {};
						dataCommit['id'] = table.cache[tableView.attr('lay-id')][trElem.data('index')]['id'];
						dataCommit[tdElem.data('field')] = value;
						t.doEditOnTable(dataCommit);
						return;
					});
					
					// 绑定选择框(转换)的值变化提交事件
					layui.form.on('switch(_input_filter_checkbox_on_table)', function(data){
						//layer.tips(this.value + ' ' + this.name + '：'+ data.elem.checked, data.othis);
						var value = this.checked ? 1 : 0;
						t.modifyTableCacheBySwitch(data, value);
					});
					
					// 绑定选择框(下拉)的值变化提交事件
					layui.form.on('select(_input_filter_selector_on_table)', function (data) {
						var table = layui.table;
						
					    var selectElem = $(data.elem);
					    var tdElem = selectElem.closest('td');
					    var trElem = tdElem.closest('tr');
					    var tableView = trElem.closest('.layui-table-view');
					    layui.table.cache[tableView.attr('lay-id')][trElem.data('index')][tdElem.data('field')] = data.value;
						
					    var dataCommit = {};
						dataCommit['id'] = table.cache[tableView.attr('lay-id')][trElem.data('index')]['id'];
						dataCommit[tdElem.data('field')] = data.value;
						t.doEditOnTable(dataCommit);
					});
					// 监听“刷新”按钮
					$('#' + t.c.id_grid_panel).find('div[lay-event="LAYTABLE_REFRESH"]').on('click',function (e) {
						layer.confirm("确定刷新吗？",{
							btn: ['确定', '取消']
						}, function (index) {
							location.reload();
							layer.close(index);
						});
					});
				}
				,error: function(res, msg){
					console.log(res, msg)
				}
			});

			//触发单元格工具事件
			layui.table.on('tool(main_table)', function(obj){ // 双击 toolDouble
				var data = obj.data;
				//console.log(obj)
				if(obj.event === 'del'){
					layer.confirm('真的删除行么', function(index){
						obj.del();
						layer.close(index);
					});
				} else if(obj.event === 'edit'){
					layer.open({
						title: '编辑',
						type: 1,
						area: ['80%','80%'],
						content: '<div style="padding: 16px;">自定义表单元素</div>'
					});
				}
			});
			
			//触发表格复选框选择
			layui.table.on('checkbox(main_table)', function(obj){
				console.log(obj)
			});
			 
			//触发表格单选框选择
			layui.table.on('radio(main_table)', function(obj){
				console.log(obj)
			});
			 
			// 单元格编辑事件
			layui.table.on('edit(main_table)', function(obj){
				var field = obj.field //得到字段
				,value = obj.value //得到修改后的值
				,data = obj.data; //得到所在行所有键值
				
				var update = {};
				update[field] = value;
				obj.update(update);
				
				var dataCommit = {};
				dataCommit['id'] = data.id;
				dataCommit[field] = value;
				
				doEditOnTable(dataCommit);
			});
			
			//行单击事件（双击事件为：rowDouble）
			layui.table.on('rowDouble(' + t.c.id_table_main + ')', function(obj){
				var that = this;
				var data = obj.data;
				if (t.c.menuId == '81'){
					t.openUrl("财务事件明细","/indexCommonOfMenu?menuId=82",1);
				}else if(t.c.menuId == '10166'){
					t.openUrl("印章申请("+data.bid+")","/web/administration/webAdmUseSignetApplyController/toEdit?id="+data.id,1);
				}else if(t.c.menuId == '119'){//店铺退出跟踪
					var w=($(window).width()*0.8);
					var h=($(window).height() - 50);
					layer.open({
						title:'详情',
						type: 2,
						area: [w+'px', h +'px'],
						fix: true,
						maxmin: false,
						shadeClose: true,
						shade:0.4,shade:0.5,
						content:'/web/business/tpShopStopPhaseRecord/toDetail?operateCompanyId=' + data.operateCompanyId + ''});
				}else if(t.c.menuId == '55'){//店铺注册跟踪
					var w=($(window).width()*0.8);
					var h=($(window).height() - 50);
					layer.open({
						title:'详情',
						type: 2,
						area: [w+'px', h +'px'],
						fix: true,
						maxmin: false,
						shadeClose: true,
						shade:0.4,shade:0.5,
						content:'/web/business/tpShopRegisterPhaseRecord/toDetail?operateCompanyId=' + data.operateCompanyId + ''});
				}else if(t.c.menuId == '10169'){
					t.openUrl("商品备案申请("+data.bid+")","/web/business/tpProductBq/toEdit?bid="+data.bid,1);
				}else if(t.c.menuId == '10201'){
					t.openUrl("运营人员登记("+data.bid+")","/web/hr/thrOperateRegistration/toEdit?id="+data.id,1);
				}else if(t.c.menuId == '10180'){
					t.openUrl("A+申请("+data.bid+")","/web/business/tpAplusSq/toEdit?bid="+data.bid,1);
				}else if(t.c.menuId == '10178'){
					t.openUrl("Listing申请("+data.bid+")","/web/business/tpProductActiveSq/toEdit?id="+data.id,1);
				}else if(t.c.menuId == '27'){
					t.openUrl("商品("+data.code+")","/web/business/tpProductBasis/toEdit?id=" + data.id,1);
				}else if(t.c.menuId == '28'){

				}else if(t.c.menuId == '10184'){//Listing库
					t.openUrl('Listing库('+data.code+') - 详情', '/web/business/tpProductActive/toEdit?id=' + data.id+"&editType=detail",1);
				}else if(t.c.menuId == '10168'){//精品库
					t.openUrl("精品库("+data.code+") - 详情","/web/business/tpBoutique/toDetail?id="+data.id+'&code='+data.code,1);
				}else if(t.c.menuId == '10167'){//站点维护
					t.openUrl('站点维护('+data.code+') - 编辑', '/web/base/tpAmazonRegion/toEdit?id=' + data.id,1);
				}else if(t.c.menuId == '10199'){//预约调拨单
					t.openUrl('预约调拨单('+data.bid+') - 编辑','/web/storage/tccAllocate/toFlow?bid='+ data.bid, 1);
				}else if(t.c.menuId == '10206'){//手工分配单
					t.openUrl('手工分配单('+data.bid+') - 编辑','/web/storage/tccDistribute/toFlow?bid='+ data.bid, 1);
				} else if (t.c.menuId == '10207'){// 预约调拨取消单
					t.openUrl('预约调拨取消单('+data.bid+') - 编辑','/web/storage/tccAllocateCancel/toFlow?bid='+ data.bid, 1);
				} else if(t.c.menuId == '10205'){//员工入职申请
					t.openUrl('员工入职申请('+data.userId+') - 详情','/web/hr/thrUserEntryApply/toDetail?id=' + data.id,1);
				}else if(t.c.menuId == '10208'){//人员档案
					t.openUrl('人员档案('+data.userId+') - 详情','/web/hr/thrUserArchives/toDetail?id=' + data.id,1);
				}else if(t.c.menuId == '10231'){//万里汇多账户管理
					t.openUrl('万里汇多账户管理('+data.accountNo+') - 编辑','/web/worldfirst/wfStore/toEdit?accountNo=' + data.accountNo,1);
				}else {
//					layer.alert(JSON.stringify(data), {
//						title: '当前行数据：'
//					});
				}
				
				//标注选中样式
				obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
			});
		},
		isFrom1_0: function() {
			if(window.top.isMobile!=undefined || window.top.isMobile!=null) {
				return false;
			} else {
				return true;
			}
		},
		openUrl: function(title, url, toType) { // toType，打开页面方式，1标签页2新页面
	    	var isOn1_0 = this.isFrom1_0();
	    	if (isOn1_0 == true) {
				window.open(url);
			} else {
				if (toType != null && toType != undefined) {
					if (toType == 1) {
						window.top.add_tab(title,url);
					} else {
						window.open(url);
					}
				}
			}
		},
		reloadGrid: function(where) {
			var t = this;
			layui.table.reload(t.c.id_table_main,{
				page: {
					curr: 1 //重新从第 1 页开始
				},
				where: where
			})
		},
		doEditOnTable: function(dataCommit) {
			var t = this;
			var indexOfLoading = layer.load(1, {
				shade: [0.5,'#000000'] //0.1透明度的白色背景
			});
			$.post(t.c.pathGridEditRequest, dataCommit, function(res){
				if (res.code == 0) {
					layer.msg(res.msg);
					layer.close(indexOfLoading);
				} else {
					layer.close(indexOfLoading);
					layer.msg(res.msg);
				}
			});
		},
		modifyTableCacheBySwitch: function(data, value) {
			var t = this;
			
		    var table = layui.table;
		    var switchElem = $(data.elem);
		    var tdElem = switchElem.closest('td');
		    var trElem = tdElem.closest('tr');
		    var tableView = trElem.closest('.layui-table-view');
		    table.cache[tableView.attr('lay-id')][trElem.data('index')][tdElem.data('field')] = value;
			
			var dataCommit = {};
			dataCommit['id'] = table.cache[tableView.attr('lay-id')][trElem.data('index')]['id'];
			dataCommit[tdElem.data('field')] = value;
			t.doEditOnTable(dataCommit);
		},
		initFormItem: function () { // 控件初始化
			var form = layui.form;
			var laydate = layui.laydate;
			form.render('select');
			var t = this;
			
			// 给搜索框的各个表单项设置高度（输入框）
			$('#' + t.c.id_panel_search_form).find('.layui-input').each(function(){
				$(this).css({'height': '30px'});
			});
			
			// 给搜索框的各个表单项设置边框及背景颜色（下拉框）
			$('#' + t.c.id_panel_search_form).find('.layui-unselect').each(function(){
				$(this).css({'background-color': '#FFFFFF', 'border': '0.1px solid #B5B5B5', 'height': '30px'});
			});
			
			// 监听输入框变化
			$('#' + t.c.id).find('input[data-filter="ysui_input_text"]').on('change',function (e) {
				var v = $(this).val();
				var index = $(this).attr('data-index');
				
				t.c.conditions[index].value = v;
			});
			
			// 初始化年份选择框
			$('#' + t.c.id).find('input[data-filter="ysui_input_year"]').each(function(){
				var index = $(this).attr('data-index');
				laydate.render({
					elem: this,
					type: 'year',
					//, max: maxtime//设置选择最大时间为当前
					calendar: false,
					btns: ['clear', 'confirm'],
					done: function (value, date) {//value是选中的值
						//选中后
						t.c.conditions[index].value = value;
					}
				});
			});
			
			// 初始化月份选择框
			$('#' + t.c.id).find('input[data-filter="ysui_input_month"]').each(function(){
				console.log(this);
				var index = $(this).attr('data-index');
				var condRangeType = $(this).attr('cond-range-type');
				if(condRangeType == 't_system') {
					var myDate = new Date();
					var maxtime = myDate.getFullYear() + "-" + (myDate.getMonth() + 1);
					laydate.render({
						elem: this
						, type: 'month'
						, format: 'yyyy-MM'
						, max: maxtime
						, calendar: true
						, btns: ['clear', 'confirm', 'now']
						, done: function (value, date) {
							//选中后
							t.c.conditions[index].value = value;
						}
					});
				} else if(condRangeType == 't_between') {
					var myDate = new Date();
					var maxtime = myDate.getFullYear() + "-" + (myDate.getMonth() + 1);
					laydate.render({
						elem: this
						, type: 'month'
						, format: 'yyyy-MM'
						, range: '~'
						, max: maxtime
						, calendar: true
						, btns: ['clear', 'confirm', 'now']
						, done: function (value, date) {
							console.log(value);
							//选中后
							t.c.conditions[index].value = value;
						}
					});
				}
			});
			
			// 初始化日期选择框（YYYY-MM-DD）
			$('#' + t.c.id).find('input[data-filter="ysui_input_date"]').each(function(){
				var index = $(this).attr('data-index');
				var condRangeType = $(this).attr('cond-range-type');
				if(condRangeType == 't_system') {
					var myDate = new Date();
					var maxtime = myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + (myDate.getDate());
					laydate.render({
						elem: this
						, type: 'date'
						, max: maxtime
						, calendar: true
						, btns: ['clear', 'confirm', 'now']
						, done: function (value, date) {
							//选中后
							t.c.conditions[index].value = value;
						}
					});
				} else if(condRangeType == 't_between') {
					var myDate = new Date();
					var maxtime = myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + (myDate.getDate());
					laydate.render({
						elem: this
						, type: 'date'
						, max: maxtime
						, range: '~'
						, calendar: true
						, btns: ['clear', 'confirm', 'now']
						, done: function (value, date) {
							console.log(value);
							//选中后
							t.c.conditions[index].value = value;
						}
					});
				}
			});
			
			// 初始化日期时间选择框（YYYY-MM-DD HH:mm:ss）
			$('#' + t.c.id).find('input[data-filter="ysui_input_datetime"]').each(function(){
				var index = $(this).attr('data-index');
				var condRangeType = $(this).attr('cond-range-type');
				if(condRangeType == 't_system') {
					var myDate = new Date();
					var maxtime = myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + (myDate.getDate()) + " 23:59:59";
					laydate.render({
						elem: this
						, type: 'datetime'
						, max: maxtime
						, calendar: true
						, btns: ['clear', 'confirm', 'now']
						, done: function (value, date) {
							//选中后
							t.c.conditions[index].value = value;
						}
					});
				} else if(condRangeType == 't_between') {
					var myDate = new Date();
					var maxtime = myDate.getFullYear() + "-" + (myDate.getMonth() + 1) + "-" + (myDate.getDate()) + " 23:59:59";
					laydate.render({
						elem: this
						, type: 'datetime'
						, max: maxtime
						, range: '~'
						, calendar: true
						, btns: ['clear', 'confirm', 'now']
						, done: function (value, date) {
							console.log(value);
							//选中后
							t.c.conditions[index].value = value;
						}
					});
				}
			});
	    },
		listenBtn:function () { // 添加监听
			var t = this;
			// 监听“显示/隐藏搜索框”按钮
			$('#' + t.c.id).find('div[data-id="icon-to-hide-and-show"]').on('click',function (e) {
				var panelForSearch = $('#' + t.c.id_panel_search_form); // 表单容器
				var panelForGrid = $('#' + t.c.id_grid_panel); // 表格容器
				var formForSearch = panelForSearch.find('form[data-id="form-for-search"]'); // 搜索表单
				var action = $(this).attr('data-action');
				
				$(this).toggle(); // 隐藏箭头图标
				if(action == 'hide') {
					formForSearch.toggle(); // 隐藏搜索表单
					panelForGrid.removeClass('width_percent_83'); // 表格容器宽度放大
					panelForGrid.addClass('width_percent_98');
					panelForSearch.find('div[data-action="show"]').slideToggle(200);
				} else if(action == 'show') {
					formForSearch.slideToggle(200); // 显示搜索表单
					panelForGrid.removeClass('width_percent_98'); // 表格容器宽度缩小
					panelForGrid.addClass('width_percent_83');
					panelForSearch.find('div[data-action="hide"]').slideToggle(200);
				}
				return;
			});
	        // 监听“查询”按钮
			$('#' + t.c.id).find('a[data-filter="filter_form_search"]').on('click',function (e) {
				console.log(t.getConds());
				layui.table.reload(t.c.id_table_main, {
					page: {curr: 1},
					where: {'conditions': JSON.stringify(t.getConds())}
				})
			});
			// 监听各个“清空”图标
			$('#' + t.c.id).find('i.layui-icon-close-fill').on('click',function (e) {
				var index = $(this).attr('data-index'); // 当前索引
				
				var condition = t.c.conditions[index];
				
				// 清除当前搜索条件的值
				$('input[data-code="' + condition.code + '"]').val('');
				t.c.conditions[index].value = '';
				t.setConds(t.c.conditions);
				return;
			});
			// 监听“清空”按钮
			$('#' + t.c.id).find('button[data-filter="filter_form_clear"]').on('click',function (e) {
				layer.confirm("确定清空搜索条件吗？",{
					btn: ['确定', '取消']
				}, function (index) {
					// 表单数据清空
					$('#' + t.c.id).find('input[type=text],select').each(function() {
						$(this).val('');
					});
					// 搜索条件数据清空（隐藏条件不处理）
					for (var i = 0; i < t.c.conditions.length; i++) {
						var condition = t.c.conditions[i];
						if(condition.type == 't_hidden') {
							continue;
						} else {
							t.c.conditions[i].value = '';
						}
					}
					t.setConds(t.c.conditions);
					layer.close(index);
				});
				return;
			});
			
			// 初始化左上角按钮工具栏监听
			layui.YsGridBtn.init({menuId: t.c.menuId, id_table_main: t.c.id_table_main, gridObj: t});
	    },
		getData:function () {
			return this.c.conditions;
		},
		setConds:function (conditions) {
			this.c.conditions = conditions;
		},
		getConds:function (type) { // 类型，空或1代表直接取对象里的值，2代表去前端重新获取
			var t = this;
			var conditionsRes = [];
			$('#' + t.c.id_panel_search_form).find('[data-form-filter="ys-search-form-item"]').each(function(){
				var v = $(this).val();
				if(v) {
					var i = $(this).attr('data-index');
					var condition = t.c.conditions[i];
					conditionsRes.push({'rangeType':condition.rangeType, 'value': v, 'field':condition.code});
				}
			});
			
			if (type == 2) {
				return {'conditions': JSON.stringify(conditionsRes)}
			} else {
				return conditionsRes;
			}
		}
	};
	/* 定义object对象【end】 */
	
	
	exports('YsGrid', object);
});

function doDeleteOnTable(url) {
    var indexOfLoading = layer.load(1, {
        shade: [0.5,'#000000'] //0.1透明度的白色背景
    });
    layer.confirm('确定删除？ ', {
            btn: ['确定','取消'] //按钮
        }, function(){
            $.post(url, function(res){
                if (res.code == 0) {
                    layer.msg(res.msg);
                    layer.close(indexOfLoading);
                    location.reload();
                } else {
                    layer.close(indexOfLoading);
                    layer.msg(res.msg);
                }
            });
        }, function(){
            layer.close(indexOfLoading);
        }
    );
}

// 进入表单页
function toFlow(bid, title) {
    $.ajax({
        type: "POST",
        url: '/api/inter/ysProcInst/getMenuIdByBid',
        data: {bid: bid},
        success: function (res) {
        	console.log(res);
        	var menuId = null;
            if (res.code == 0) {
            	menuId = res.data;
            } else {
                alert('加载页面失败，请检查菜单的流程配置');
            }
            /*
             * 此处根据不同菜单ID，跳转不同的表单页
             */
            if (menuId == 70) {
            	openUrl(title, '/web/finance/tcwRunningBack/toFlow?bid=' + bid);
			} else if (menuId == 10166) {//印章申请
				openUrl(title, '/web/administration/webAdmUseSignetApplyController/toEdit?bid=' + bid);
			} else if (menuId == 10169) {
				openUrl(title, '/web/business/tpProductBq/toEdit?bid=' + bid);
			}else if(menuId == '10180'){
				openUrl(title, '/web/business/tpAplusSq/toEdit?bid=' + bid);
			}else if (menuId == 10199) {
            	openUrl(title, '/web/storage/tccAllocate/toFlow?bid=' + bid);
			} else if (menuId == 10201) {//运营人员登记
				openUrl(title, '/web/hr/thrOperateRegistration/toFlow?bid=' + bid);
			} else if (menuId == 10205) {//人员申请
				openUrl(title, ' /web/hr/thrUserEntryApply/toEdit?bid=' + bid);
			} else if (menuId == 10206) {
            	openUrl(title, '/web/storage/tccDistribute/toFlow?bid=' + bid);
			} else if (menuId == 10207) {
				openUrl(title, '/web/storage/tccAllocateCancel/toFlow?bid=' + bid);
			} else {
				alert('请先设置好表单页面路径');
			}
        }
    });
}

function openUrl(title, url) {
	if (!window.top.is_on_1_5) {
		window.open(url);
	} else {
		window.top.add_tab(title, url);
	}
}